<template>
  <q-page class="flex flex-top">
    <q-toolbar class="absolute-top" style="width: 100%">
      <q-breadcrumbs
        class="text-grey-8"
        active-color="blank"
        style="font-size: 16px; width: 100%"
      >
        <q-breadcrumbs-el
          label="根目录"
          icon="home"
          class="clickable"
          @click="
            () => {
              resourcePath.resourceId = null;
              gotoStorePage();
            }
          "
        />
        <q-breadcrumbs-el
          :label="item.name"
          class="clickable"
          v-for="item in resourcePath.path"
          :key="item.id"
          @click="
            () => {
              resourcePath.resourceId = item.id;
              gotoStorePage();
            }
          "
        />
      </q-breadcrumbs>

      <q-space />

      <q-btn
        icon="fa-solid fa-arrow-up-right-from-square"
        color="primary"
        flat
        rounded
        size="sm"
        v-close-popup
        v-if="shareUrl"
        :href="shareUrl"
        target="_blank"
      />

      <q-toggle
        v-if="resourceId"
        v-model="status"
        :icon="status ? 'fa-regular fa-eye' : 'fa-regular fa-eye-slash'"
        @update:model-value="updateStatus"
      />

      <q-btn
        icon="fa-solid fa-panorama"
        color="primary"
        flat
        rounded
        size="sm"
        v-close-popup
        @click="LoadImgLinks"
      >
        <q-popup-edit auto-save>
          图床选择，图片会上传到图床上
          <q-list style="width: 200px">
            <q-item
              tag="label"
              v-ripple
              v-for="img_link in imgLinks"
              :key="img_link.id"
            >
              <q-item-section avatar>
                <q-radio
                  v-model="imgLink"
                  :val="img_link.id"
                  @update:model-value="UpdateImgLink"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ img_link.dir }}</q-item-label>
                <q-item-label caption>{{ img_link.updateTime }} </q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-popup-edit>
      </q-btn>
    </q-toolbar>
    <MdEditor
      v-model="text"
      class="blog-eidtor"
      :style="{
        height: `${$q.screen.height - 50 - 50 - 24}px`,
        marginTop: '50px',
      }"
      @on-save="saveBlog"
      @on-upload-img="uploadImg"
      @on-error="onError"
    />
  </q-page>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import URLSearch from "src/utility/URLSearch";
import { api, session, basePath } from "src/boot/axios";
import { useQuasar, copyToClipboard } from "quasar";
import notify from "src/utility/notify";
import { useRouter } from "vue-router";
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";

const status = ref(false);
const router = useRouter();
const resourcePath = reactive({
  path: [],
  resourceId: null,
});
const resourceId = ref(null);
const isLoading = ref(false);
const $q = useQuasar();
const text = ref("# Hello Editor");
const imgLinks = ref([]);
const imgLink = ref(null);

const onError = (err) => {
  notify.error(err.message);
};

const uploadImg = async (files, callback) => {
  if (!resourceId.value) return;
  if (!imgLink.value) {
    notify.info(
      "你还没有设置博客的图床，不能上传图片到服务器，点击右上角的图片按钮来设置博客图床吧！",
    );
    return;
  }
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((rev, rej) => {
        const form = new FormData();
        form.append("file", file);

        api
          .post("/blog/image/upload", form, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((res) => rev(res))
          .catch((error) => rej(error));
      });
    }),
  );

  callback(res.map((item) => item.data.url));
};

const shareUrl = ref(null);

const updateStatus = async (val) => {
  isLoading.value = true;
  try {
    let response = null;
    if (val) {
      response = await api.post("/blog/share/publish/" + resourceId.value);
    } else {
      response = await api.delete("/blog/share/publish/" + resourceId.value);
    }
    notify.success(response.data.message);
    if (response.data.url) {
      window.open(`${location.origin}/#${response.data.url}`);
      shareUrl.value = `${location.origin}/#${response.data.url}`;
    } else {
      shareUrl.value = null;
    }
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`更新博客状态失败: ` + ex.message);
      console.error(ex);
    }
  } finally {
    isLoading.value = false;
  }
};

const saveBlog = async () => {
  if (!resourceId.value) return;

  isLoading.value = true;
  try {
    const response = await api.put("/blog/" + resourceId.value, {
      c: text.value,
    });
    notify.success(response.data.message);
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`保存失败: ` + ex.message);
      console.error(ex);
      imgLinks.value = [];
    }
  } finally {
    isLoading.value = false;
  }
};

const UpdateImgLink = async (val) => {
  isLoading.value = true;
  try {
    const response = await api.post("/blog/image/links/" + val);
    notify.success(response.data.message);
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`更新博客图床失败: ` + ex.message);
      console.error(ex);
      imgLinks.value = [];
    }
  } finally {
    isLoading.value = false;
  }
};

const LoadImageLink = async () => {
  isLoading.value = true;
  try {
    const response = await api.get("/blog/image/link");
    imgLink.value = response.data.data;
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`获取博客图床失败: ` + ex.message);
      console.error(ex);
      imgLinks.value = [];
    }
  } finally {
    isLoading.value = false;
  }
};

const LoadImgLinks = async () => {
  isLoading.value = true;
  try {
    const response = await api.get("/blog/image/links");
    imgLinks.value = response.data.items;
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`获取博客图床列表失败: ` + ex.message);
      console.error(ex);
      imgLinks.value = [];
    }
  } finally {
    isLoading.value = false;
  }
};

const gotoStorePage = () => {
  if (resourcePath.resourceId) {
    window.open(
      location.origin +
        "/#/application/cloud?ResourceId=" +
        resourcePath.resourceId,
    );
  } else {
    window.open(location.origin + "/#/application/cloud");
  }
};

const getParentResource = async () => {
  isLoading.value = true;
  let resourceId = resourcePath.resourceId;
  if (!resourceId) resourceId = "";
  try {
    const response = (await api.get("/cloud/?resource_id=" + resourceId)).data;
    resourcePath.path = response.path;

    if (response.dir) {
      resourcePath.resourceId = response.dir.id;
    } else {
      resourcePath.resourceId = null;
    }

    resourcePath.path = response.path;
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`获取资源失败: ` + ex.message);
      console.error(ex);
    }
    resourcePath.resourceId = null;
  } finally {
    isLoading.value = false;
  }
};

const getResource = async () => {
  isLoading.value = true;
  try {
    const response = await api.get("/blog/" + resourceId.value);
    text.value = response.data.content;
    resourcePath.resourceId = response.data.parentId;
    await getParentResource();
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`获取博客图床列表失败: ` + ex.message);
      console.error(ex);
      imgLinks.value = [];
    }
  } finally {
    isLoading.value = false;
  }
};

const getDemo = async () => {
  isLoading.value = true;
  try {
    const response = await api.get(`${location.origin}/assets/MarkdownDemo.md`);
    text.value = response.data;
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`获取Demo示例失败: ` + ex.message);
      console.error(ex);
    }
  } finally {
    isLoading.value = false;
  }
};

const onloadPageInfo = async () => {
  const params = URLSearch.getAllQueryParams();
  if (params && params.ResourceId) {
    resourceId.value = params.ResourceId;
    console.log("Get Resource id:", resourceId.value);
  }
  if (resourceId.value) {
    await getResource();
  } else {
    await getDemo();
  }
};

const getPublishStatus = async () => {
  if (!resourceId.value) return;

  isLoading.value = true;
  try {
    let response = await api.get("/blog/share/publish/" + resourceId.value);
    status.value = response.data.status;
    if (status.value) {
      shareUrl.value = `${location.origin}/#${response.data.url}`;
    }
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      console.error(ex);
    }
  } finally {
    isLoading.value = false;
  }
};

onMounted(async () => {
  await onloadPageInfo();
  await LoadImageLink();
  await getPublishStatus();
});
</script>

<style lang="sass" scoped>
.my-custom-toggle
  border: 1px solid #027be3
</style>
